package com.foodorder.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminFixController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @GetMapping("/public/fix-admin")
    public Map<String, Object> fixAdminPassword() {
        Map<String, Object> result = new HashMap<>();
        try {
            String password = "123456";
            String encodedPassword = passwordEncoder.encode(password);
            
            // 检查管理员是否存在
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM admins WHERE username = ?", 
                Integer.class, 
                "admin"
            );
            
            if (count != null && count > 0) {
                // 更新密码
                jdbcTemplate.update(
                    "UPDATE admins SET password = ? WHERE username = ?",
                    encodedPassword, "admin"
                );
                result.put("code", 200);
                result.put("message", "管理员密码已重置为: " + password);
            } else {
                // 插入新管理员
                jdbcTemplate.update(
                    "INSERT INTO admins (username, password, name, phone, email, avatar, role, status, permissions, created_at, updated_at) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
                    "admin", encodedPassword, "系统管理员", "13800138000", "admin@foodorder.com", 
                    "/images/avatars/admin.jpg", "SUPER_ADMIN", "ACTIVE", "ALL"
                );
                result.put("code", 200);
                result.put("message", "已创建新的管理员账号，密码为: " + password);
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "修复管理员密码时出错: " + e.getMessage());
        }
        return result;
    }
} 